package com.kgc.service.impl;

import com.kgc.document.Ticket;
import com.kgc.repository.TicketRepository;
import com.kgc.service.TicketSolrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.solr.core.query.result.HighlightEntry;
import org.springframework.data.solr.core.query.result.HighlightPage;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TicketSolrServiceImpl implements TicketSolrService {

    @Autowired
    private TicketRepository ticketRepository;

    @Override
    public int getTicketInfoCount_CY(String content) {
        int count = ticketRepository.countByTitle(content);


        return count;
    }

    @Override
    public List<Ticket> getTicketInfoList_CY(String title, Integer pageNow, Integer pageSize) {

        PageRequest pageRequest=PageRequest.of(pageNow,pageSize);


        HighlightPage<Ticket> highlightPage =ticketRepository.findByTitle(title,pageRequest);


        //获取含有高亮字段的所有结果
        List<HighlightEntry<Ticket>> highlighted = highlightPage.getHighlighted();
        //替换普通字段为高亮



        for(HighlightEntry<Ticket> highlightEntry:highlighted){
            Ticket ticket = highlightEntry.getEntity();//普通结果
            List<HighlightEntry.Highlight> highlights = highlightEntry.getHighlights();//高亮结果
            //遍历
            for (HighlightEntry.Highlight highlight:highlights) {

                String filedTitle =highlight.getField().getName();

                String snipplets=highlight.getSnipplets().get(0);
                //替换为高亮内容
                if(filedTitle.equals("title")){
                    ticket.setTitle(snipplets);
                }else if(filedTitle.equals("performer")){
                    ticket.setPerformer(snipplets);
                }else if(filedTitle.equals("city")){
                    ticket.setCity(snipplets);
                }
            }
        }

        //返回最终结果
        List<Ticket> contents = highlightPage.getContent();
        for (Ticket tickets:contents) {
            System.out.println(tickets);
        }

        return contents;
    }
}
